package com.dimension.service.impl;

import cn.hutool.json.JSONUtil;
import com.dimension.entity.Admin;
import com.dimension.mapper.AdminMapper;
import com.dimension.service.AdminService;
import com.dimension.utils.JwtUtil;
import com.dimension.utils.SessionUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class AdminServiceImpl implements AdminService {
    private AdminMapper adminMapper = SessionUtil.getMapper(AdminMapper.class);

    @Override
    public Integer adminLogin(String username, String password, HttpServletResponse resp) {
        Admin admin = adminMapper.adminLogin(username, password);
        if (admin == null) {
            return 1;
        }

        try {
            String token = JwtUtil.createToken(admin);
            Cookie cookie1 = new Cookie("admin", URLEncoder.encode(JSONUtil.toJsonStr(admin), "utf-8"));
            Cookie cookie2 = new Cookie("adminToken", URLEncoder.encode(token, "utf-8"));
            cookie1.setPath("/");
            cookie2.setPath("/");
            resp.addCookie(cookie1);
            resp.addCookie(cookie2);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }
}
